//
//  STSportingMapViewController.m
//  STBest
//
//  Created by apple on 2017/8/28.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "STSportingMapViewController.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <Masonry.h>
#import "STSportingChangeMapTypeViewController.h"
#import "STSportingManager.h"
#import <objc/runtime.h>
#import "STAlphaAnimator.h"
/*
 文件中的类 是否仅仅是这个文件的一部分
 
 // 分类的属性如何写
 */
@interface MAPolyline(Color)

@property (strong, nonatomic)   UIColor     *lineColor;

@end

@implementation MAPolyline(Color)

- (void)setLineColor:(UIColor *)lineColor{
    objc_setAssociatedObject(self, @"linColor", lineColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UIColor *)lineColor{
    
   return  objc_getAssociatedObject(self, @"linColor");
}

@end

@interface STSportingMapViewController ()<MAMapViewDelegate,UIPopoverPresentationControllerDelegate>

// 地图类
@property(strong, nonatomic) MAMapView  *mapView;

// 距离
@property (weak, nonatomic) IBOutlet UILabel    *distanceLabel;

// 时长
@property (weak, nonatomic) IBOutlet UILabel    *durationLabel;

@property (weak, nonatomic) IBOutlet UIButton *pauseButton;

@property (weak, nonatomic) IBOutlet UIButton *resumeButton;
@property (weak, nonatomic) IBOutlet UIImageView *gpsStateImageView;

@end

@implementation STSportingMapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupMapView];
    
    // 自定义专场动画
    [self setupModalAnimation];
    
    
    for ( STSportingTrackingLine *line in _SportingMgr.sportingsportingTracking.lines) {
        
        [self addLine:line];
    }
    
    // 通知管理代码
    [self setupNotifications];
    
    // 程序启动时刷新运动状态和界面之间的关系
    [self refreshUIWithState:_SportingMgr.state];
    
    /*
     MVVM 核心 Model + View + ViewModel -> 本质 数据 <绑定> 界面
     // 响应式编程
     
     */
    
     [self refreshUIWithGPSState:_SportingMgr.gpsState];
}

// 给地图添加一个线段
- (void)addLine:(STSportingTrackingLine *)line{
    // 如果地图上想要添加线段就必须 创建MAoverlay 协议的实例
    // MAPolyline 实现了这个协议
    
    // 创建坐标点数组
    CLLocationCoordinate2D point[2];
    point[0] = line.beginLocation.coordinate;
    point[1] = line.endLocation.coordinate;
    
    MAPolyline *polyline = [MAPolyline polylineWithCoordinates:point count:2];
    
    // 基于速度来计算线段颜色 -> 获取线段的速度
    // 设置线段的颜色
    
    // R G B
    // 绿色 0 255 0
    // 红色 255 0 0
    
    // 颜色的百分比
    CGFloat colorPercent = 0;// 0 - 1.0
    // 速度 运动有类型
    switch (_SportingMgr.sportingsportingTracking.type) {
        case STSportingTrackingTypeRun:
            // 线段的当前速度  / 人跑步的最大速度
            colorPercent = line.speed / 30.0;
            break;
        case STSportingTrackingTypeWalk:
            colorPercent = line.speed / 6.0;
            break;
        case STSportingTrackingTypeRide:
            colorPercent = line.speed / 100.0;
            break;
            
        default:
            break;
    }
    
    if(colorPercent > 1.0) colorPercent = 1.0;
    
    // 根据颜色百分比逻辑划分
    polyline.lineColor = [UIColor colorWithRed:colorPercent green:(1.0 - colorPercent) blue:0 alpha:1];
 
    [self.mapView addOverlay:polyline];
}

#pragma mark - action方法 -
- (IBAction)closeAction:(id)sender {
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}
- (IBAction)actionChangeMapType:(id)sender {
    
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Sporting" bundle:nil];
    // 苹果自带有popover功能
    // 1. 创建目标视图控制器
    STSportingChangeMapTypeViewController *vc  =[sb instantiateViewControllerWithIdentifier:@"STSportingChangeMapTypeViewController"];
    vc.type = self.mapView.mapType;
    
    
    __weak typeof(self) weakself = self;
     vc.completedBlock = ^(MAMapType type) {
      
         weakself.mapView.mapType = type;
    };
    
    
    // 设置popover 呈现样式
    vc.modalPresentationStyle = UIModalPresentationPopover;
    
    // 2. 获取包含目标视图控制器的popover控制器
    UIPopoverPresentationController *popoverController = vc.popoverPresentationController;
    
    // 注意事项
    // 必须设置代理 UIPopoverPresentationControllerDelegate 继承自UIAdaptivePresentationControllerDelegate
    // 要实现 UIAdaptivePresentationControllerDelegate 的- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller;
    // 因为默认显示全屏，虽然popover但是还是全屏显示，所以我们需要手动设置 关闭全屏显示
    popoverController.delegate = self;
    
    // 设置 popover 的属性
    // 设置箭头
    popoverController.permittedArrowDirections = UIPopoverArrowDirectionDown;
    popoverController.sourceView = sender;
    
    //设置呈现的大小
    vc.preferredContentSize = CGSizeMake(0, 150);
    
    //进行呈现
    [self presentViewController:vc animated:YES completion:nil];
}
- (IBAction)actionPause:(id)sender {
    [_SportingMgr pause];
}

- (IBAction)actionResume:(id)sender {
    [_SportingMgr resume];
}
// 关闭全屏显示
- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller{
    return UIModalPresentationNone;
}
- (void)setupMapView{
    
    
    ///初始化地图
    self.mapView = [[MAMapView alloc] initWithFrame:self.view.bounds];
    
    ///把地图添加至view
    [self.view insertSubview:self.mapView atIndex:0];
    
    //显示用户当前位置
    self.mapView.showsUserLocation = YES;
    
    //设置代理
    self.mapView.delegate = self;
    
    //跟踪用户位置
    self.mapView.userTrackingMode = MAUserTrackingModeFollow;
    
    //约束
    [self.mapView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    // 设置指南针位置
    CGFloat margin = 10;
    self.mapView.compassOrigin = CGPointMake(_ScreenWidth - self.mapView.compassSize.width - margin, margin + _StatusBarHeight);
}

#pragma mark - 通知管理 -
- (void)setupNotifications {
    
    // 监视线段被添加后回调
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sporingTrackingLineDidBeGeneratedNotification:) name:STSporingTrackingLineDidBeGeneratedNotification object:_SportingMgr];
    
    // 监听运动状态发生变化
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sportingStateDidChangedNotification:) name:STSportingStateDidChangedNotification object:_SportingMgr];
    
    // 监视GPS状态发生改变时回调
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sportingGPSStateDidChangedNotification:) name:STSportingGPSStateDidChangedNotification object:_SportingMgr];
    
}

// 当线段被生成的时候引发通知
- (void)sporingTrackingLineDidBeGeneratedNotification:(NSNotification *)notification {
    // 把新生成的线段添加到地图中
    STSportingTrackingLine *line = notification.userInfo[kSporingTrackingLine];
    [self addLine:line];
    
    // 更新距离信息
    self.distanceLabel.text = [NSString stringWithFormat:@"%.2f",_SportingMgr.sportingsportingTracking.distance];
    
    // 更新运动的时长
    self.durationLabel.text = _SportingMgr.sportingsportingTracking.durationString;
}

// 运动状态发生变化时候回调
- (void)sportingStateDidChangedNotification:(NSNotification *)notification{
    
    STSportingState state = [notification.userInfo[kState] integerValue];
    
    [self refreshUIWithState:state];
}

// 当gps状态发生变化时回调
- (void)sportingGPSStateDidChangedNotification:(NSNotification *)notification {
    STSportingGPSState state = [notification.userInfo[kGPSState] integerValue];
    [self refreshUIWithGPSState:state];
}

#pragma mark - 构建UI -
// 自定义专场动画
- (void)setupModalAnimation {
//    // 1. 设置视图的专场样式(自定义)
//    self.modalPresentationStyle = UIModalPresentationCustom;
//    
//    self.animator = [STAlphaAnimator new];
//    
//    // 2. 设置专场代理
//    self.transitioningDelegate = self.animator;
    
    
}

#pragma mark - 刷新UI -
// 描述 state 和界面之间的关系
- (void)refreshUIWithState:(STSportingState)state {
    switch (state) {
        case STSportingStateUnsport:
            
            self.pauseButton.hidden = YES;
            self.resumeButton.hidden = YES;
            break;
            
        case STSportingStateSporting:
            self.pauseButton.hidden = NO;
            self.resumeButton.hidden = YES;
            break;
            
        case STSportingStatePaused:
            self.pauseButton.hidden = YES;
            self.resumeButton.hidden = NO;
            break;
        default:
            break;
    }
}

// 描述 gpsState 于 界面之间的关系
- (void)refreshUIWithGPSState:(STSportingGPSState)gpsState {
    switch (gpsState) {
        case STSportingGPSStateDisconnect:
            self.gpsStateImageView.image = _I(@"ic_sport_gps_map_disconnect");
            break;
        case STSportingGPSStateGood:
            self.gpsStateImageView.image = _I(@"ic_sport_gps_map_connect_3");
            break;
        case STSportingGPSStateNormal:
            self.gpsStateImageView.image = _I(@"ic_sport_gps_map_connect_2");
            break;
            
        case STSportingGPSStateBad:
            self.gpsStateImageView.image = _I(@"ic_sport_gps_map_connect_1");
            break;
            
        default:
            break;
    }
}
- (void)dealloc{
    [self teardownNotifications];
}

- (void)teardownNotifications {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


#pragma mark - MAMapViewDelegate -
- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id <MAOverlay>)overlay{
    
    MAPolylineRenderer *rend = [[MAPolylineRenderer alloc] initWithOverlay:overlay];
    
    MAPolyline *polyline = (MAPolyline*)overlay;
    //设置线宽
    rend.lineWidth = 5.0;
    rend.strokeColor = polyline.lineColor;
    rend.lineCapType = kMALineCapRound;
    
    return rend;
}
@end
